/**
 * Created by mac on 2017/7/3.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ScrollView,
    StatusBar,
    ListView,
    DeviceEventEmitter,
    Animated,
    Easing

} from 'react-native';


import Swiper from 'react-native-swiper';

import Api from './Api';

let allData = require('./data.json');

import NavigationView from './NavigtionView';
import Channels from './Channels';
import Cat from './Cat';
import Recommend from './Recommend';
import FlashSale from './FlashSale';
import DragCart from './DragCart';
import ScrollCard from './ScrollCard';
import Promotions from './Promotions';
import Articles from './Articles';
import Products from './Products';
import FloatView from './FloatView';
import  SectionBar from './SectionBar';
import CommentProducts from './CommentProducts';
import CommentPros from './CommentPros';

import {CachedImage} from "react-native-img-cache";

let width = Dimensions.get('window').width;
let height= Dimensions.get('window').height;

//let Url = 'https://wx.3songshu.com:88/mobile/api/index/info';

Url = 'https://wx.3songshu.com:88/mobile/api/index/recommendList/1';

let footHeight = 0;
let headerHeight = 88;
let viewHeight = headerHeight;

export default  class  Home extends Component{

    // 构造
      constructor(props) {
        super(props);

          let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        // 初始状态
        this.state = {
            opacity:1.0,
            dataSource:ds.cloneWithRows(['row1']),
            cartImy:'none',
            floatViewY:-160,
            currentPage:0,
            commentProducts:[],
            scrollImageViews:[],
            cartImages:[],
            display:'none',
            pageCount:parseInt(viewHeight/320),

        };
      }

    componentDidMount() {
          Api.Get(Url,null,this.success.bind(this),this.error.bind(this))

         this.subscription = DeviceEventEmitter.addListener('ClickCart',this.clickCart.bind(this));


        let scrollImageViews = [];
        allData.data.carousel.map(function(item,i){
            let v = (
                <View style={{flex:1,backgroundColor:'red'}}>
                    <CachedImage style={{width:width,height:width/8*5}} key={i} source={{uri:item.pic}}/>
                </View>
            )

            scrollImageViews.push(v);

        })

        this.setState({
            scrollImageViews:scrollImageViews,
        })


    }

    componentDidUpdate() {

        if(this.state.pageCount == parseInt(viewHeight/320)){
            return;
        }
         this.setState({
             pageCount:parseInt(viewHeight/320),
         })

    }
    componentWillUnmount(){
        this.subscription.remove();
    };

    clickCart(point){

        console.log('x='+point.x);
        console.log('y='+point.y);


        let ToX = width*7/10 - point.x;
        let ToY = height - 40 - point.y;



        this.spinValue = new Animated.Value(0);

        const x = this.spinValue.interpolate({
            inputRange: [0,0.5,1],
            outputRange: [0,point.x>width*7/10?-50:50,ToX]
        })
        const y = this.spinValue.interpolate({
            inputRange: [0,0.5,1],
            outputRange: [0,-50,ToY]
        })

        let cartImage = (
            <Animated.Image source={require('./images/add-to-cart-img@2x.png')} style={{width:27,height:33, position:'absolute',top:point.y,left:point.x,transform: [{translateX: x},{translateY:y}]}}/>
        )

        let cartImages = this.state.cartImages;
        if(cartImages.length == 0){

            cartImages.push(cartImage);
        }
        else {
            cartImages.splice(0,1,cartImage);
        }

        this.setState({
            cartImages:cartImages,
        })

        this.spin()

    }


    spin () {
        this.spinValue.setValue(0)
        Animated.timing(
            this.spinValue,
            {
                toValue: 1,
                duration: 1000,
                easing: Easing.linear,
                useNativeDriver:true
            }
        ).start((finished) =>{
            if (finished) {
                DeviceEventEmitter.emit('ClickCartComplete')
            }
        })
    }


    success(resData){

        console.log('成功');
        console.log(resData);

        this.setState({
            commentProducts:resData,
        })
    }

    error(resData){
        console.log('失败');
        console.log(resData);
    }


    codeCallBack(){


    }






    render(){

        return(
            <View style={{height:height-49}}>
                <ListView
                    keyboardShouldPersistTaps='always'
                    keyboardDismissMode='on-drag'
                    ref={(e)=>this.listView = e}
                    dataSource={this.state.dataSource}
                    scrollEventThrottle={1}
                    contentInset={{top:20}}
                    contentOffset={{x:0,y:-20}}
                    onScroll={e=>{
                        let y =  e.nativeEvent.contentOffset.y;

                        let floatViewY = this.state.floatViewY;

                        floatViewY += y;

                        if (floatViewY > 40){

                            floatViewY = 40;

                        this.setState({
                            display:'flex',
                         })
                        }

                        if (y < 40){

                            floatViewY -=80;
                            if(floatViewY < -160) {
                                floatViewY = -160;
                            }
                        }


                        let currentPage = parseInt(y/320+1);


                        this.setState({
                            floatViewY:floatViewY,
                            currentPage:currentPage,
                        })

                        if (y >= -20 ){

                            console.log('y='+y);

                            this.setState({
                                opacity:1-(y+20)*0.025,
                            })
                        }
                        else {
                            this.setState({
                                opacity:1,
                            })
                        }
                    }}

                    renderRow={()=><View/>}
                    renderSectionHeader={()=>{
                        return (
                            <Channels codeCallBack={this.codeCallBack()}/>
                        )
                    }}

                    renderHeader={()=>{
                        return (
                            <View>
                                <NavigationView  opacity={this.state.opacity}/>
                                    <Swiper loop={true}
                                            index={0}
                                            autoplay={true}
                                            autoplayTimeout={3}
                                            horizontal={true}
                                            pagingEnabled
                                            showsPagination={true}
                                            height={width/8*5}
                                            stickySectionHeadersEnabled={true}
                                            contentContainerStyle={[styles.contentContainer, {flexDirection: 'row'}]}
                                            dotColor="lightgray"
                                            activeDotColor="white"
                                            paginationStyle={{width:50,height:20,left:width-60,bottom:-5}}
                                            dotStyle={{ width: 10,
                                                height: 3,
                                                borderRadius: 2,}}
                                            activeDotStyle={{ width: 10,
                                                height: 3,
                                                borderRadius: 2,
                                            }}>
                                        {this.state.scrollImageViews}
                                    </Swiper>
                            </View>
                            )
                        }}

                    renderFooter={()=>{
                        return (
                            <View onLayout={(e)=>{
                                let h = e.nativeEvent.layout.height;
                                if (h > footHeight){
                                    viewHeight = (viewHeight - footHeight + h);
                                    footHeight = h;
                                }
                            }}>
                                <Cat/>
                                <Recommend/>
                                <DragCart/>
                                <FlashSale clickCart={(point)=>this.clickCart(point)}/>
                                <Promotions/>
                                <Articles/>
                                <Products clickCart={(point)=>this.clickCart(point)}/>
                                <SectionBar title={'大家正在热评的零食'}/>
                                <CommentPros clickCart={(point)=>this.clickCart(point)} data={this.state.commentProducts}/>
                            </View>
                        )
                     }}>

                </ListView>
                    {this.state.cartImages}
                <FloatView  count={this.state.pageCount} currentPage={this.state.currentPage} click={()=>{
                    this.listView.scrollTo({y:0})
                }} ref={(e)=>this.floatView=e}  display={this.state.display} style={{position:'absolute',right:10,bottom:this.state.floatViewY}}/>
            </View>

        )
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white',
    },
    contentContainer: {
        width:2*width,
        height:200,
    },
    menuContainer: {
        flexDirection: 'row',
    },

    pageControl: {
        margin: 10,
    },
    indicatorUnSelected:{
        backgroundColor:'rgba(255,255,255,.2)',
        width: 8,
        height: 3,
        borderRadius: 2,
        marginLeft: 3,
        marginRight:3,
        marginTop:3,
        marginBottom: 3,
    },
    indicatorSelected:{
        backgroundColor:'rgba(255,255,255,1)',
        width: 8,
        height: 3,
        borderRadius: 2,
        marginLeft: 3,
        marginRight:3,
        marginTop:3,
        marginBottom: 3,
    },
});

